//
//  shaidanViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/12/10.
//  Copyright © 2015年 szb. All rights reserved.
//

#import "shaidanViewController.h"
#import "ZYQAssetPickerController.h"
#import "AppDelegate.h"
#import "BPhttpTool.h"
#import "QiniuSDK.h"
#import "MBProgressHUD+MJ.h"
#import "AccountTool.h"

@interface shaidanViewController ()<ImageAddPreViewDelegate>{
    
    ZYQAssetPickerController *_picturePicker;
}

@end

@implementation shaidanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.photosView.y = 180.0f;
    //self.photosView.backgroundColor = [UIColor lightGrayColor];
    self.textView.placehoder = @"说说你和这件小物的故事吧...";
    
    
    UIButton *picture = [UIButton buttonWithType:UIButtonTypeCustom];
    picture.frame = CGRectMake(15.0f, 120, 80, 30);
    [self.textView addSubview:picture];
    [picture setTitle:@"晒照片" forState:UIControlStateNormal];
    [picture setBackgroundColor:BPGlobaBGColor];
    [picture addTarget:self action:@selector(addAlasset) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"晒单" style:UIBarButtonItemStylePlain target:self action:@selector(sendShai)];
}

- (void)sendShai
{
    if (self.photosView.images.count > 0) {
        [BPhttpTool get:[NSString stringWithFormat:@"%@Upload/get_qiniu_token",BPhttp] params:nil success:^(id responseObj) {
            NSString *token = [responseObj valueForKey:@"token"];
            QNUploadManager *uploadManager = [[QNUploadManager alloc] init];
            NSMutableArray *shaiPicArry = [NSMutableArray array];
            for (int i = 0; i < self.photosView.images.count; i ++) {
                
                CGImageRef ref = [[self.photosView.assetArry[i] defaultRepresentation]fullScreenImage];
                UIImage *alasset = [[UIImage alloc] initWithCGImage:ref];
                NSData *imageData = UIImageJPEGRepresentation(alasset, 0.05);
                
                [uploadManager putData:imageData key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                    [shaiPicArry addObject:resp[@"key"]];
                    
                    if (shaiPicArry.count == self.photosView.images.count) {
                        NSString *Imagestring = [shaiPicArry componentsJoinedByString:@","];
                        NSDictionary *param = @{@"mid":self.orderID,
                                                @"uid":[AccountTool account].uid,
                                                @"content":self.textView.text,
                                                @"pics":Imagestring,
                                                @"type":@"2",
                                                };
                        [BPhttpTool post:[NSString stringWithFormat:@"%@appapi/share",BPhttp] params:param success:^(id responseObj) {
                            NSDictionary *dic = responseObj;
                            if ([dic[@"status"] intValue] == 1) {
                                [MBProgressHUD showSuccess:@"晒单成功"];
                                self.block();
                            }
                            BPLog(@"%@",responseObj);
                        } failure:^(NSError *error) {
                            [MBProgressHUD showError:@"晒单失败"];
                        }];
                        
                    }
                } option:nil];
            }
            
        } failure:^(NSError *error) {
            [MBProgressHUD showError:@"晒单失败"];
            
        }];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [MBProgressHUD showError:@"请添加照片"];
    }
}

- (void)addAlasset
{
    if (_picturePicker == nil) {
        _picturePicker = [[ZYQAssetPickerController alloc] init];
        _picturePicker.assetsFilter = [ALAssetsFilter allPhotos];
        _picturePicker.showEmptyGroups = NO;
    }
    
    _picturePicker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    [[D_Main_Appdelegate preview] reMoveAllResource];
    [D_Main_Appdelegate showPreView];
    [D_Main_Appdelegate preview].isAddPic = YES;
    [[D_Main_Appdelegate preview] setUpYunPromptLabel:3];
    [D_Main_Appdelegate preview].picnum = 3;
    [[D_Main_Appdelegate preview].readyMakeBtn setTitle:@"马上晒单" forState:UIControlStateNormal];
    _picturePicker.vc = self;
    [self presentViewController:_picturePicker animated:YES completion:nil];
    [D_Main_Appdelegate preview].delegateSelectImage = self;
}

- (void)startPintuAction:(ImageAddPreView *)sender
{
    [self.photosView addAlasset:[D_Main_Appdelegate preview].imageassets];
    [_picturePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
